<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue';
import type {GetType} from "@/type/GetType";
import {deleteData, getAllEvent, getAllUsers, post, put} from "@/net";
import {ElMessage, ElMessageBox, ElTable} from "element-plus";
import {Delete, EditPen} from "@element-plus/icons-vue"
import {zhCn} from 'element-plus/es/locale/index.mjs';
// 状态变量
const dialogAddVisible = ref(false);
const dialogUpdateVisible = ref(false);
// 功能函数
const fetchEventListAndRefresh = () => {
  getAllEventData();
};
const handlerOperationResult = (success: boolean) => {
  if (success) {
    fetchEventListAndRefresh();
  }
};

const closeUpdataDialog = () => {
  dialogUpdateVisible.value = false;
};
const closeAddDialog = () => {
  dialogAddVisible.value = false;
};

const handlerUpdateSelectChange = (um: string) => {
  const index = username.findIndex(user => user.username === um);
  if (um in username) {
    addEventForm.org_uid = username[index].uid;
    addEventForm.org_username = username[index].username;
  }
}
const handleAddSelectChange = (hm: string) => {
  const index = username.findIndex(username => username.username === hm);
  if (hm in username) {
    addEventForm.org_uid = username[index].uid;
    addEventForm.org_username = username[index].username;
  }
}

// 增加房屋
let addEventForm = reactive({
  name: '',
  type: '',
  time: '',
  address: '',
  org_uid: 0,
  org_username: '',
  remark: '',
});
const submitAddEvent = () => {
  post('api/activity/add', addEventForm, () => {
    ElMessage.success("添加成功");
    fetchEventListAndRefresh();
    handlerOperationResult(true);
  }, () => {
    ElMessage.warning("添加失败")
    fetchEventListAndRefresh();
    closeAddDialog();
  }, () => {
    ElMessage.error("发生了错误");
    fetchEventListAndRefresh();
    closeAddDialog();
  })
}
// 删除房屋
const handleDeleteEvent = (index: number, row: EventType) => {
  ElMessageBox.confirm("你要删除活动吗?", "提示", {
    icon: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  }).then(() => {
    deleteData("api/activity/delete", {id: row.id}, () => {
      ElMessage.success("删除成功");
      handlerOperationResult(true);
    }, () => {
      ElMessage.warning("删除失败,")
    }, () => {
      ElMessage.error("删除error")
    });
  }).catch((err) => {
    ElMessage.error(err)
  })
};
// 修改房屋
let updateEventForm = reactive({
  id: 0,
  name: '',
  type: '',
  time: '',
  address: '',
  org_uid: 0,
  org_username: '',
  remark: '',
});

const handleUpdateEvent = (row: Partial<typeof updateEventForm>) => {
  Object.keys(row).forEach(key => {
    if (updateEventForm.hasOwnProperty(key)) {
      (updateEventForm as any)[key] = (row as any)[key];  // 或者使用更安全的类型断言或类型守卫
    }
  });
  dialogUpdateVisible.value = true;
};
const submitUpdateEvent = () => {
  const index = eventData.findIndex(item => item.id === updateEventForm.id);
  const oldData = eventData[index];
  let newData = reactive({
    id: 0,
    name: '',
    type: '',
    time: '',
    address: '',
    org_uid: 0,
    org_username: '',
    remark: '',
  })
  for (let key in updateEventForm) {
    if (updateEventForm.hasOwnProperty(key) &&
        updateEventForm[key as keyof typeof updateEventForm] !== oldData[key as keyof typeof oldData]) {
      newData[key as keyof typeof newData] = updateEventForm[key as keyof typeof updateEventForm];
    } else {
      newData[key] = null;
    }
  }
  newData.id = updateEventForm.id;
  newData.org_uid = updateEventForm.org_uid;
  try {
    put('api/activity/update', newData, () => {
      ElMessage.success("修改成功");
      handlerOperationResult(true);
    })
  } catch (err) {
    ElMessage.error("发生了错误");
  }
}

// 获取房屋
interface EventType {
  id: number;
  name: string;
  type: string;
  time: string;
  address: string;
  org_uid: number;
  username: string;
  remark: string;
}

let eventData: EventType[] = reactive([]);

const getAllEventData = async () => {
  try {
    const res: GetType = await getAllEvent('/api/activity/getAll');
    eventData.splice(0, eventData.length, ...res.message);
  } catch (e) {
    console.log(e)
  }
}

// 生命周期函数

onMounted(() => {
  getAllEventData();
  getAllUser_name();
})
// 时间变量
const dataPicker = ref(new Date());

// 用户变量

interface UserNameType {
  username: string;
  uid: number;
}

const username = reactive<UserNameType[]>([]);
const getAllUser_name = async () => {
  try {
    const res: GetType = await getAllUsers('/api/user/getAllName');
    username.splice(0, username.length, ...res.message.filter((user: any) => user.name !== null));
  } catch (e) {
    console.log(e)
  }
};


</script>

<template>

  <div style="display: flex; flex-flow: row nowrap; justify-content: space-between; margin-bottom: 10px">
    <div>
      <span>活动管理 > 活动信息</span>
    </div>
    <div style="margin-right: 60px">
      <el-button type="primary" @click="dialogAddVisible = true" id="add_activity">添加活动</el-button>
    </div>
  </div>

  <el-table ref="table" :data="eventData" style="width: 100%"
            height="70vh" border
  >
    <el-table-column type="index" label="序号"/>
    <el-table-column prop="username" label="组织者"/>
    <el-table-column prop="name" label="活动详情"/>
    <el-table-column prop="type" label="活动类型"/>
    <el-table-column prop="address" label="活动地址"/>
    <el-table-column prop="time" label="时间"/>
    <el-table-column prop="remark" label="备注"/>
    <el-table-column label="操作">
      <template #default="scope">
        <el-button name="update" @click="handleUpdateEvent(scope.row)" type="warning" :icon="EditPen" circle/>
        <el-button name="delete" plain @click="handleDeleteEvent(scope.$index,scope.row)" type="danger" :icon="Delete"
                   circle/>
      </template>

    </el-table-column>
  </el-table>

  <el-dialog
      title="添加活动信息"
      :model-value="dialogAddVisible"
      width="50%"
      @close="closeAddDialog"
  >
    <el-form label-width="auto"
             label-position="left"
             label-suffix=":"
             style="width: 500px;"
             v-model="addEventForm"
    >
      <el-form-item :required="true" label="活动名称">
        <el-input v-model="addEventForm.name"/>
      </el-form-item>
      <el-form-item :required="true" label="活动类型">
        <el-input v-model="addEventForm.type"/>
      </el-form-item>
      <el-form-item :required="true" label="活动时间">
        <el-config-provider :locale="zhCn">
          <el-date-picker
              v-model="dataPicker"
              :size="'large'"
              type="date"
              placeholder="选择日期"
          />
        </el-config-provider>
      </el-form-item>
      <el-form-item :required="true" label="活动地址">
        <el-input v-model="addEventForm.address"/>
      </el-form-item>
      <el-form-item :required="true" label="活动组织者">
        <el-select v-model="addEventForm.org_username"
                   placeholder="请选择"
                   prop="org_username"
                   @change="handleAddSelectChange"
        >
          <el-option
              v-for="item in username"
              :key="item.uid"
              :label="item.username"
              :value="item.uid"
          />
        </el-select>
      </el-form-item>
      <el-form-item :required="true" label="备注">
        <el-input v-model="addEventForm.remark"/>
      </el-form-item>
      <el-form-item >
        <el-button type="primary" @click="submitAddEvent">提交</el-button>
        <el-button @click="closeAddDialog">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!--  修改房屋  -->
  <el-dialog
      title="修改活动信息"
      :model-value="dialogUpdateVisible"
      width="50%"
      @close="closeUpdataDialog"
  >
    <el-form label-width="auto"
             label-position="left"
             label-suffix=":"
             style="width: 500px;"
    >
      <el-form-item :required="true" label="活动名称">
        <el-input v-model="updateEventForm.name"/>
      </el-form-item>
      <el-form-item :required="true" label="活动类型">
        <el-input v-model="updateEventForm.type"/>
      </el-form-item>
      <el-form-item :required="true" label="活动时间" >
        <el-config-provider :locale="zhCn">
          <el-date-picker
              v-model="dataPicker"
              :size="'large'"
              type="date"
              placeholder="选择日期"
          />
        </el-config-provider>
      </el-form-item>
      <el-form-item :required="true" label="活动地址">
        <el-input v-model="updateEventForm.address"/>
      </el-form-item>
      <el-form-item :required="true" label="活动组织者">
        <el-select v-model="updateEventForm.org_username"
                   placeholder="请选择"
                   prop="username"
                   @change="handlerUpdateSelectChange"
        >
          <el-option
              v-for="user in username"
              :key="user.uid"
              :label="user.username"
              :value="user.username"
          />
        </el-select>

      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="updateEventForm.remark"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitUpdateEvent">提交</el-button>
        <el-button @click="closeUpdataDialog">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

</template>

<style scoped>

.el-form > .el-form-item {
  margin-bottom: 20px;
  margin-left: 100px;
  width: 350px;
}
</style>